import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import axios from 'axios'

const getTodos = () => {
	return axios.get('https://jsonplaceholder.typicode.com/todos')
}
// action
export const todoGet = createAsyncThunk(
	'todo/get', // action
	async (
		_paramaters, // 参数
		_thunkAPI // 工具
	) => {
		const response = await getTodos()
		return response.data
	}
)

// reducer
interface TodoState {
	todoList: Array<{ title: string; id: number }>
	loading: boolean
	error: string | null
}
export const todoSlice = createSlice({
	name: 'todo',
	initialState: {
		todoList: [],
		loading: false,
		error: null
	} as TodoState,
	// 处理同步
	reducers: {},
	// 处理异步(必须createAsyncThunk创建)
	extraReducers: (builder) => {
		builder.addCase(todoGet.pending, (state) => {
			state.loading = true
		})
		builder.addCase(todoGet.fulfilled, (state, action) => {
			console.log('action', action.payload)
			state.todoList = action.payload?.slice(0, 10)
			state.loading = false
			state.error = null
		})
		builder.addCase(todoGet.rejected, (state, action) => {
			state.loading = false
			state.error = action.payload as string | null
		})
	}
})
